package com.cn.springcloudwechat.serviceImpl;

import com.cn.springcloudwechat.common.utils.ErrorUtil;
import com.cn.springcloudwechat.common.utils.ThreadLocalUtil;
import com.cn.springcloudwechat.mapper.mapper.YmAnswerMapper;
import com.cn.springcloudwechat.mapper.mapper.YmPraiseMapper;
import com.cn.springcloudwechat.mapper.mapper.attachment.YmAttachmentMapper;
import com.cn.springcloudwechat.mapper.mapper.find.askDoctor.YmDoctorMapper;
import com.cn.springcloudwechat.model.YmAnswer;
import com.cn.springcloudwechat.model.YmPraise;
import com.cn.springcloudwechat.model.YmUser;
import com.cn.springcloudwechat.model.attachment.YmAttachment;
import com.cn.springcloudwechat.model.dto.AttachmentDto;
import com.cn.springcloudwechat.model.find.askDoctor.YmDoctor;
import com.cn.springcloudwechat.model.find.communication.YmAnswerVO;
import com.cn.springcloudwechat.service.YmAnswerService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.*;

@Service
public class YmAnswerServiceImpl implements YmAnswerService {
    @Autowired
    private YmAnswerMapper ymAnswerMapper;
    @Autowired
    YmDoctorMapper ymDoctorMapper;
    @Autowired
    YmPraiseMapper ymPraiseMapper;
    @Autowired
    YmAttachmentMapper ymAttachmentMapper;


    /**
     * 问医生-快速提问
     * @param ymAnswer， douctorConsultTypeId
     * @return List<YmAnswer>
     */
    @Override
    @Transactional
    public String[] insertYmAnswer(YmAnswer ymAnswer, Long doctorId) {

        String answerDes = ymAnswer.getAnswerDes();
        Assert.notNull(answerDes,String.format(ErrorUtil.PARAMETER_ISNULL,"answerDes"));
        String relevanceId = null;
        String relevanceTypeId = null;
        String[] relevanceIdAndrelevanceTpyeId = new String[2];

        // 获取医生信息
        YmDoctor ymDoctor = ymDoctorMapper.selectByPrimaryKey(doctorId);
        // 获取用户信息
        YmUser user = ThreadLocalUtil.getUser();
        Long answerUserId = user.getUserId();
        ymAnswer.setAnswerUserId(answerUserId);
//        ymAnswer.setAnswerUserId(44L);
        // 判断医生是否为平台推荐医生
        Short recommend = ymDoctor.getRecommend();
        if(recommend == 1){
       // 修改医生的剩余可提问数
            ymDoctor.setDoctorId(doctorId);
            ymDoctorMapper.updateByPrimaryKeySelective(ymDoctor);
        }
        Long  parentId = ymAnswer.getTypeId();
        ymAnswer.setParentId(parentId);
            Integer result = ymAnswerMapper.insertSelective(ymAnswer);
            if(result == 0){
                // result等于null说明新增失败抛出异常
                throw new IllegalArgumentException(ErrorUtil.ASK_DOCTOR_ERROR);
            }else{
                relevanceId = ymAnswer.getAnswerId().toString();
                relevanceTypeId = ymAnswer.getType().toString();
                relevanceIdAndrelevanceTpyeId[0] = relevanceId;
                relevanceIdAndrelevanceTpyeId[1] = relevanceTypeId;
            }
        return relevanceIdAndrelevanceTpyeId;
    }


    /**
     * 问医生-提问回复
     * @param ymAnswer， douctorConsultTypeId
     * @return List<YmAnswer>
     */
    @Override
    public String[] insertYmAnswerReply(YmAnswer ymAnswer) {
        String answerDes = ymAnswer.getAnswerDes();
        Assert.notNull(answerDes,String.format(ErrorUtil.REPLY_CONTENT_NULL,"answerDes"));
        String relevanceId = null;
        String relevanceTypeId = null;
        String[] relevanceIdAndrelevanceTpyeId = new String[2];
        // 获取用户信息
        YmUser user = ThreadLocalUtil.getUser();
        Long answerUserId = user.getUserId();
        ymAnswer.setAnswerUserId(answerUserId);
//       ymAnswer.setAnswerUserId(44L);
            Integer result = ymAnswerMapper.insertSelective(ymAnswer);
        if(result == 0){
            // result等于0说明新增失败抛出异常
            throw new IllegalArgumentException(ErrorUtil.ASK_DOCTOR_ERROR);
        }else{
            relevanceId = ymAnswer.getAnswerId().toString();
            relevanceTypeId = ymAnswer.getType().toString();
            relevanceIdAndrelevanceTpyeId[0] = relevanceId;
            relevanceIdAndrelevanceTpyeId[1] = relevanceTypeId;
        }
        return relevanceIdAndrelevanceTpyeId;
    }
    /**
     * 问医生- 删除提问(提问时附件上传失败删除提问内容)
     * @param  answerId
     * @return int
     */
    @Override
    public Integer deleteYmAnswer(Long answerId) {
        return ymAnswerMapper.deleteByPrimaryKey(answerId);
    }


    /**
     * 问医生-向指定医生提问
     * @param  ymAnswer
     * @return int
     */
    @Override
    public Integer insertYmAnswerByDoctorId(YmAnswer ymAnswer) {
        Assert.notNull(ymAnswer,String.format(ErrorUtil.PARAMETER_NULL,"ymAnswer"));
        Integer result = ymAnswerMapper.insertSelective(ymAnswer);
        if(result == 0){
            // result等于0说明提问失败抛出异常
            throw new IllegalArgumentException(ErrorUtil.ASK_DOCTOR_ERROR);
        }else{
            return result;
        }
    }

    /**
     * 问医生-查询当前用户的所有提问(列表查询)
     * @param  answerUserId,type
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String,Object>> queryYmAnswerDetailByAnswerUserId(Long typeId, Long answerUserId, Integer type) {
        Assert.notNull(answerUserId,String.format(ErrorUtil.PARAMETER_NULL, "answerUserId"));
        Assert.notNull(type,String.format(ErrorUtil.PARAMETER_NULL, "type"));
        List<Map<String,Object>> list = new ArrayList<>();
        List<YmAnswerVO> ymAnswerList = ymAnswerMapper.queryYmAnswerDetailByAnswerUserId(typeId,answerUserId,type);
        for (YmAnswerVO ymAnswerVO:ymAnswerList) {
            Long answerId = ymAnswerVO.getAnswerId();
            Map<String,Object> map = new HashMap<>();
            YmPraise ymPraise = new YmPraise();
            ymPraise.setPraiseTypeId(answerId);
            ymPraise.setPraiseType("2");
            Integer count = ymPraiseMapper.praiseCount(ymPraise);
            map.put("ymAnswerVO",ymAnswerVO);
            map.put("count",count);
            map.put("answersCount",ymAnswerList.size());
            list.add(map);
        }
        return list;
    }
    /**
     * 问医生-根据answerId和typeId查询当前用户提问医生的回复
     * @param typeId,,answerId,type
     * @return List<YmAnswer>
     */

    @Override
    public List<YmAnswer> queryYmAnswerDetailByTypeId(Long typeId, Long answerUserId, Integer type) {
        return this.ymAnswerMapper.queryYmAnswerDetailByTypeId(typeId,answerUserId,type);
    }

    /**
     * 问医生-查询属于当前医生的所有提问
     * @param typeId,,praiseType,type
     * @return List<YmAnswer>
     */
    @Override
    public List<YmAnswerVO> queryYmAnswerListByTypeId(Long typeId, Integer type, String praiseType) {
        // 查询提问列表
        List<YmAnswerVO> ymAnswerVOList = ymAnswerMapper.queryYmAnswerListByTypeId(typeId,type);
        List<AttachmentDto> attachmentDtos = ymAttachmentMapper.queryAllUrl();

        // 拼装数据
        for (YmAnswerVO ymAnswerVO:ymAnswerVOList) {
            // 查询附件
            List<YmAttachment> ymAttachments = new ArrayList<YmAttachment>();
            for (AttachmentDto attachmentDto: attachmentDtos) {
                YmAttachment ymAttachment = new YmAttachment();
                if (ymAnswerVO.getAnswerId().equals(attachmentDto.getAttId())){
                    ymAttachment.setAttachmentUrl(attachmentDto.getUrl());
                    ymAttachments.add(ymAttachment);
                }
            }
            ymAnswerVO.setYmAttachments(ymAttachments);
            // 查询回复数
            Long parentAnswerId = ymAnswerVO.getAnswerId();
            Integer answersCount = ymAnswerMapper.queryYmAnswerCount(typeId, type, parentAnswerId);
            // 设置回复数
            ymAnswerVO.setAnswersCount(answersCount);
        }
        return ymAnswerVOList;
    }

    /**
     * 问医生-查询当前用户的所有提问(列表查询)
     * @param  type
     * @return List<Map<String,Object>>
     */
    @Override
    public List<Map<String,Object>> queryYmAnswersByAnswerUserId(Integer type) {
        Assert.notNull(type,String.format(ErrorUtil.PARAMETER_NULL,"type"));
        // 获取用户信息
        YmUser user = ThreadLocalUtil.getUser();
        Long answerUserId = user.getUserId();
//        Long answerUserId = 44L;
        List<Map<String,Object>> list = new ArrayList<>();
        List<YmAnswerVO> ymAnswerList = ymAnswerMapper.queryYmAnswersByAnswerUserId(answerUserId,type);
        List<AttachmentDto> attachmentDtos = ymAttachmentMapper.queryAllUrl();
        for (YmAnswerVO ymAnswerVO:ymAnswerList) {
            Long answerId = ymAnswerVO.getAnswerId();
            List<YmAttachment> ymAttachments = new ArrayList<YmAttachment>();
            for (AttachmentDto attachmentDto: attachmentDtos) {
                YmAttachment ymAttachment = new YmAttachment();
                if (ymAnswerVO.getAnswerId().equals(attachmentDto.getAttId())){
                    ymAttachment.setAttachmentUrl(attachmentDto.getUrl());
                    ymAttachments.add(ymAttachment);
                }
            }
            ymAnswerVO.setYmAttachments(ymAttachments);
            Map<String,Object> map = new HashMap<>();
            YmPraise ymPraise = new YmPraise();
            ymPraise.setPraiseTypeId(answerId);
            ymPraise.setPraiseType("2");
            Integer count = ymPraiseMapper.praiseCount(ymPraise);
            map.put("ymAnswerVO",ymAnswerVO);
            map.put("count",count);
            map.put("answersCount",ymAnswerList.size());
            list.add(map);
        }
        return list;
    }

    /**
     * 问医生-点击用户一条提问，查看回复明细
     * @param  typeId,nswerUserId
     * @return List<Map<String,Object>>
     */
    @Override
    public Map<String, Object> queryYmAnswerListDetail(Long typeId, Long answerId, String praiseType) {
        Assert.notNull(typeId,String.format(ErrorUtil.PARAMETER_NULL,"typeId"));
        Assert.notNull(answerId,String.format(ErrorUtil.PARAMETER_NULL,"answerId"));
        // 获取用户信息
        YmUser ymUser = ThreadLocalUtil.getUser();
        Long userId = ymUser.getUserId();
//        Long userId = 44L;
        List<YmAnswerVO> ymAnswerList = ymAnswerMapper.queryYmAnswerDetailByTypeIdAndAnswerUserId(typeId,answerId);
        YmAnswerVO ymAnswerVO = ymAnswerMapper.selectByPrimaryKey(answerId);
        List<AttachmentDto> attachmentDtos = ymAttachmentMapper.queryAllUrl();
        List<YmAttachment> ymAttachments = new ArrayList<YmAttachment>();
        for (AttachmentDto attachmentDto: attachmentDtos) {
            YmAttachment ymAttachment = new YmAttachment();
            if (answerId.equals(attachmentDto.getAttId())){
                ymAttachment.setAttachmentUrl(attachmentDto.getUrl());
                ymAttachments.add(ymAttachment);
            }
        }
        // 查询被回复人名字
        for (YmAnswerVO ymAnswerVO1:ymAnswerList ) {
            if (null != ymAnswerVO1.getParentId()){
                String parentName = ymAnswerMapper.queryParentName(ymAnswerVO1.getParentId());
                ymAnswerVO1.setParentName(parentName);
            }
        }
        ymAnswerVO.setYmAttachments(ymAttachments);
        Map<String,Object> map = new HashMap<>();
        // 查询点赞状态和点赞数
        YmPraise ymPraise = new YmPraise();
        Long praiseTypeId = ymAnswerVO.getAnswerId();
        ymPraise.setPraiseTypeId(praiseTypeId);
        Integer praiseCountNumber = ymPraiseMapper.queryPraiseCount(praiseType, praiseTypeId);
        ymPraise.setUserId(userId);
        ymPraise.setPraiseType(praiseType);
        Integer state = ymPraiseMapper.praiseExist(ymPraise);
        if(null == state || "".equals(state)){
            state = 0;
        }
        // 设置点赞数
        ymAnswerVO.setPraiseCountNumber(praiseCountNumber);
        // 设置点赞状态
        ymAnswerVO.setPraiseState(state);
        // 设置回复数
        ymAnswerVO.setAnswersCount(ymAnswerList.size());
        map.put("ymAnswerVO",ymAnswerVO);
        map.put("ymAnswerList",ymAnswerList);
        return map;
    }

    @Override
    public Long getAnswerQuantity(Long typeId, Integer type) {
        Assert.notNull(typeId,String.format(ErrorUtil.PARAMETER_NULL, "typeId"));
        Assert.notNull(type,String.format(ErrorUtil.PARAMETER_NULL, "type"));
        Long list=ymAnswerMapper.getAnswerQuantity(typeId,type);
        return list;
    }
}
